var express = require('express');
var router = express.Router();
const Ptick = require('../db/pticklist');

// Get all pticks
router.get('/list', async (req, res, next) => {
  try {
    const { name } = req.query;
    const filter = {};
    if (name) {
      filter.name = { $regex: name, $options: 'i' }; // Case-insensitive search
    }
    const pticks = await Ptick.find(filter).sort({ id: 1 });
    res.json({
      code: 200,
      data: pticks,
      message: '获取成功'
    });
  } catch (err) {
    next(err);
  }
});

// Add pticks
router.post('/add', async (req, res, next) => {
  try {
    const tasks = req.body; // expecting an array of tasks
    const currentTime = new Date().toLocaleString()

    const maxIdResult = await Ptick.find().sort({ id: -1 }).limit(1);
    let currentId = maxIdResult.length > 0 ? maxIdResult[0].id : 0;

    const newTasks = tasks.map(task => {
        currentId++;
        let statusType = 'gray';
        let progress = '0%';
        if (task.status === '已完成') {
            statusType = 'blue';
            progress = '100%';
        } else if (task.status === '进行中') {
            statusType = 'orange';
            progress = '50%'; // Assuming in-progress is 50%
        }

        return {
            ...task,
            id: currentId,
            statusType: statusType,
            progress: progress,
            createTime: currentTime,
            updateTime: currentTime
        }
    });

    const result = await Ptick.insertMany(newTasks);
    res.json({
      code: 200,
      data: result,
      message: '添加成功'
    });
  } catch (err) {
    next(err);
  }
});

// Delete a ptick
router.post('/delete/:id', async (req, res, next) => {
  try {
    const { id } = req.params;
    const result = await Ptick.findOneAndDelete({ id: id });
    if (result) {
      res.json({
        code: 200,
        message: '删除成功'
      });
    } else {
      res.status(404).json({
        code: 404,
        message: '未找到任务'
      });
    }
  } catch (err) {
    next(err);
  }
});

module.exports = router;